﻿using System;
using Telerik.Web.UI;
using System.Data;
using System.Configuration;
using FlexCel.Core;
using System.IO;

namespace EXAM.Admin.Page_Admin
{
    public partial class Test : System.Web.UI.Page
    {
        string sErr = "";
        string _db = "EXA";
        string _connDes = ConfigurationSettings.AppSettings["strDesConnection"].ToString();
        string _connSrc = "";
        string _pathTemp = "~/Template";
        string _pathReport = "~/Report";
        private string Type2Type(string val)
        {
            switch (val)
            {
                case "TST":
                    return "Testing";
                case "TMP":
                    return "Test Review";
            }
            return "";
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadComboType();
                LoadComboLevel();
                LoadComboCate();
                LoadComboTopic();
                LoadDataAccess(cboANAL_T9);
            }
        }
        private void LoadDataAccess(RadComboBox cbo)
        {
            BUS.LIST_DAControl ctr = new BUS.LIST_DAControl();
            cbo.DataSource = ctr.GetAll(ref sErr);
            cbo.DataTextField = "DAG_ID";
            cbo.DataValueField = "DAG_ID";
            cbo.DataBind();
        }
        private void LoadComboCate()
        {
            BUS.GadgetItemsControl ctr = new BUS.GadgetItemsControl();
            DataTable dt = ctr.GetParentName(Type2Type(cboType.SelectedValue), ref sErr);
            cboANAL_T0.DataSource = dt;
            cboANAL_T0.DataTextField = "Parent";
            cboANAL_T0.DataValueField = "Parent";
            cboANAL_T0.DataBind();
        }
        private void LoadComboTopic()
        {
            BUS.GadgetItemsControl ctr = new BUS.GadgetItemsControl();
            DataTable dt = ctr.GetByGadget(cboANAL_T0.SelectedValue, Type2Type(cboType.SelectedValue), ref sErr);
            cboANAL_T2.DataSource = dt;
            cboANAL_T2.DataTextField = "Name";
            cboANAL_T2.DataValueField = "Name";
            cboANAL_T2.DataBind();
        }
        private void LoadComboLevel()
        {
            LoadAnal(cboANAL_T1, "T1");
        }
        private void LoadComboType()
        {
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[] { new DataColumn("Code"), new DataColumn("Name") });
            DataRow newrow = dt.NewRow();
            newrow["Name"] = "Testing";
            newrow["Code"] = "TST";
            dt.Rows.Add(newrow);
            newrow = dt.NewRow();
            newrow["Name"] = "Test Review";
            newrow["Code"] = "TMP";
            dt.Rows.Add(newrow);
            cboType.DataSource = dt;
            cboType.DataBind();
        }
        public string GetTypeName(string val)
        {
            switch (val)
            {
                case "TST":
                    return "Testing";
                default:
                    return "Learning";
            }
        }
        protected void btnNew_Click(object sender, EventArgs e)
        {
            RefreshForm("");
            cboType.Enabled = true;
        }

        private void RefreshForm(string val)
        {
            cboANAL_T9.Text = cboANAL_T2.Text = cboANAL_T1.Text = cboANAL_T0.Text = txtRangeIP.Text = txtDescription.Text = txtID.Text = txtName.Text = val;
            txtDuration.Value = txtMaxS.Value = txtPassS.Value = txtRightS.Value = txtTimeout.Value = txtWrongS.Value = 0;
            dpTimeB.SelectedDate = dpTimeE.SelectedDate = null;

            ckEnable.Checked = ckR2U.Checked = ckRanAO.Checked = ckRanAS.Checked = ckRanQO.Checked = ckRanQS.Checked = false;
            lbErr.Text = val;
            btnPrint.Enabled = btnTemplate.Enabled = false;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            DTO.TestInfo Inf = new DTO.TestInfo();
            if (cboType.SelectedValue == "Testing" && txtDuration.Value == 0)
            {
                lbErr.Text = "Please input duration time!";
                return;
            }
            Inf = GetDataFromForm(Inf);

            BUS.TestControl ctr = new BUS.TestControl();
            if (txtID.Text != "" && txtID.Text != "-1")
            {
                sErr = ctr.Update(Inf);
                if (sErr != "")
                    lbErr.Text = sErr;
                else lbErr.Text = "Update successful";
            }
            else
            {
                txtID.Text = ctr.Add(Inf, ref sErr).ToString();
                if (sErr != "")
                    lbErr.Text = sErr;
                else lbErr.Text = "Insert successful";
            }
            if (sErr == "")
                btnPrint.Enabled = btnTemplate.Enabled = true;
            dgvList.Rebind();
        }

        private DTO.TestInfo GetDataFromForm(DTO.TestInfo Inf)
        {
            Inf.Description = txtDescription.Text;
            Inf.Duration_Time = Convert.ToInt32(txtDuration.Text);
            if (txtID.Text != "" && txtID.Text != "-1")
            {
                Inf.ID = Convert.ToInt64(txtID.Text);

            }
            else btnPrint.Enabled = btnTemplate.Enabled = false;
            Inf.Max_Score = Convert.ToInt32(txtMaxS.Text);
            Inf.Name = txtName.Text;
            Inf.Pass_Score = Convert.ToInt32(txtPassS.Text);
            Inf.Ip_range = txtRangeIP.Text;
            Inf.Score_Right = Convert.ToInt32(txtRightS.Text);
            Inf.Logout_On_Timeout = Convert.ToInt32(txtTimeout.Text);
            Inf.Score_Wrong = Convert.ToInt32(txtWrongS.Text);
            Inf.Begin_Time = BUS.CommonControl.ConvertDateToInt(dpTimeB.SelectedDate);
            Inf.End_Time = BUS.CommonControl.ConvertDateToInt(dpTimeE.SelectedDate);
            Inf.Enabled = ckEnable.Checked;
            Inf.Results_To_User = ckR2U.Checked;
            Inf.Random_Answers_O = ckRanAO.Checked;
            Inf.Random_Answers_S = ckRanAS.Checked;
            Inf.Random_Question_O = ckRanQO.Checked;
            Inf.Random_Question_S = ckRanQS.Checked;
            Inf.ANAL_T0 = cboANAL_T0.Text;
            Inf.ANAL_T1 = cboANAL_T1.Text;
            Inf.ANAL_T2 = cboANAL_T2.Text;
            Inf.ANAL_T9 = cboANAL_T9.Text;

            Inf.Type = cboType.SelectedValue;
            return Inf;
        }
        private void SetDataToForm(DTO.TestInfo Inf)
        {
            txtDescription.Text = Inf.Description;
            txtDuration.Value = Inf.Duration_Time;
            if (Inf.ID != -1)
            {
                txtID.Text = Inf.ID.ToString();
                btnPrint.Enabled = btnTemplate.Enabled = true;
                //cboType.Enabled = false;
            }
            txtMaxS.Text = Inf.Max_Score.ToString();
            txtName.Text = Inf.Name;
            txtPassS.Text = Inf.Pass_Score.ToString();
            txtRangeIP.Text = Inf.Ip_range;
            txtRightS.Text = Inf.Score_Right.ToString();
            txtTimeout.Text = Inf.Logout_On_Timeout.ToString();
            txtWrongS.Text = Inf.Score_Wrong.ToString();
            dpTimeB.SelectedDate = BUS.CommonControl.ConvertIntToDate(Inf.Begin_Time);
            dpTimeE.SelectedDate = BUS.CommonControl.ConvertIntToDate(Inf.End_Time);
            ckEnable.Checked = Inf.Enabled;
            ckR2U.Checked = Inf.Results_To_User;
            ckRanAO.Checked = Inf.Random_Answers_O;
            ckRanAS.Checked = Inf.Random_Answers_S;
            ckRanQO.Checked = Inf.Random_Question_O;
            ckRanQS.Checked = Inf.Random_Question_S;
            cboANAL_T0.Text = Inf.ANAL_T0;
            cboANAL_T1.Text = Inf.ANAL_T1;
            cboANAL_T2.Text = Inf.ANAL_T2;
            cboANAL_T9.Text = Inf.ANAL_T9;
            cboType.SelectedValue = Inf.Type;
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            foreach (GridItem item in dgvList.SelectedItems)
            {
                if (item.ItemIndex >= 0)
                {
                    string id = item.OwnerTableView.DataKeyValues[item.ItemIndex]["ID"].ToString();
                    BUS.TestControl ctr = new BUS.TestControl();
                    sErr = ctr.Delete(Convert.ToInt64(id));
                }

            }
            dgvList.Rebind();
        }

        protected void dgvList_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            if (e.CommandName.ToUpper() == "SELECTED")
            {
                string id = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ID"].ToString();
                BUS.TestControl ctr = new BUS.TestControl();
                SetDataToForm(ctr.Get(Convert.ToInt64(id), ref sErr));
                lbErr.Text = "";
            }
            else if (e.CommandName.ToUpper() == "DETAIL")
            {
                string id = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ID"].ToString();
                Session["TestID"] = id;
                Response.Redirect("TestLog.aspx");
            }
        }

        protected void dgvList_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            BUS.TestControl ctr = new BUS.TestControl();
            DataTable dt = ctr.GetByType(cboType.SelectedValue, ref sErr);

            BUS.LIST_DAControl daCtr = new BUS.LIST_DAControl();
            DTO.UserInfo usrinf = Session["UserAdmin"] as DTO.UserInfo;
            DataTable dtPermision = daCtr.GetPermissionByRole(usrinf.GroupCode, ref sErr);
            if (dtPermision.Rows.Count == 0)
                dt.Rows.Clear();
            for (int i = dt.Rows.Count - 1; i >= 0; i--)
            {
                DTO.TestInfo testInf = new DTO.TestInfo(dt.Rows[i]);
                string flag = "";
                bool ie = true;
                foreach (DataRow row in dtPermision.Rows)
                {
                    if (testInf.ANAL_T9.Trim() != "")
                    {
                        if (testInf.ANAL_T9 == row["DAG_ID"].ToString())
                        {
                            flag = row["EI"].ToString();
                        }
                        else if (row["EI"].ToString() == "I")
                        {
                            ie = false;
                        }
                    }
                }
                if ((flag == "" && ie) || flag == "I")
                {
                }
                else
                {
                    dt.Rows.Remove(dt.Rows[i]);
                }

            }
            dgvList.DataSource = dt;
        }

        protected void btnDetail_Click(object sender, EventArgs e)
        {
            if (txtID.Text != "" && txtID.Text != "-1")
            {
                Session["TestID"] = txtID.Text;
                Response.Redirect("TestTemplate.aspx");
            }
        }

        protected void cbo_ANAL_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            LoadAnal((RadComboBox)sender, ((RadComboBox)sender).ID.Replace("cboANAL_", ""));
        }
        private void LoadAnal(RadComboBox cbo, string cate)
        {
            BUS.SSRFANVControl ctr = new BUS.SSRFANVControl();
            DataTable dt = ctr.GetCategory_SSRFANV(_db, cate, ref sErr);
            cbo.DataSource = dt;
            cbo.DataTextField = "Code";
            cbo.DataValueField = "Code";
            cbo.DataBind();
        }

        protected void cboType_ItemDataBound(object sender, RadComboBoxItemEventArgs e)
        {
            e.Item.Text = ((DataRowView)e.Item.DataItem)["Name"].ToString();
            e.Item.Value = ((DataRowView)e.Item.DataItem)["Code"].ToString();
        }

        protected void btnPrint_Click(object sender, EventArgs e)
        {
            _pathTemp = MapPath(_pathTemp) + "/";
            _pathReport = MapPath(_pathReport) + "/";
            DataSet dset = new DataSet();
            bool flag = CreateTest(ref dset);
            BUS.TestControl ctr = new BUS.TestControl();
            DTO.TestInfo inf = ctr.Get(Convert.ToInt64(txtID.Text), ref sErr);
            DataTable dt = inf.ToDataTable();
            dt.Rows.Add(inf.ToDataRow(dt));
            dt.TableName = "tst";

            dset.Tables.Add(dt);
            if (flag)
            {
                ReportGenerator rg = new ReportGenerator(dset, "PRN_TEST", _db, _connDes, _pathTemp, _pathReport);
                ExcelFile file = rg.ExportExcel(_pathReport);
                using (MemoryStream ms = new MemoryStream())
                {
                    file.Save(ms);
                    ms.Position = 0;
                    Response.Clear();
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + "PRN_TEST" + ".xls");
                    Response.AddHeader("Content-Length", ms.Length.ToString());
                    Response.ContentType = "application/excel";
                    Response.BinaryWrite(ms.ToArray());
                    Response.End();
                }
            }
            else lbErr.Text = "Print Test fail";
        }
        private bool CreateTest(ref DataSet dset)
        {

            //Session[_dsetName] = dset;
            //txtTestID.Text = Session["TestID"].ToString();
            //Session["TestID"] = null;
            BUS.TestControl testCtr = new BUS.TestControl();
            DTO.TestInfo testInf = testCtr.Get(Convert.ToInt64(txtID.Text), ref sErr);
            BUS.Test_LogControl logCtr = new BUS.Test_LogControl();
            int No = logCtr.GetNoTemp(Convert.ToInt64(txtID.Text), cboType.SelectedValue);
            if (No <= 0)
                return false;
            //txtNo.Text = No.ToString();
            int iToday = BUS.CommonControl.ConvertDateToInt(DateTime.Today);
            if (!dset.Tables.Contains("dtQuest"))
            {
                DataTable dtQuest = new DataTable();
                if (testInf.Random_Question_S || testInf.Random_Question_O)
                    dtQuest = logCtr.GetLogRandByNo(No, ref sErr);
                else
                    dtQuest = logCtr.GetLogByNo(No, ref sErr);


                dtQuest.TableName = "dtQuest";

                dset.Tables.Add(dtQuest.Copy());

                //DataRelation relat = new DataRelation("reQuest_Ans", new DataColumn[] { dtQuest.Columns["No"], dtQuest.Columns["Line"] }, new DataColumn[] { dtAnswer.Columns["Test_Log_No"], dtAnswer.Columns["Test_Log_Line"] });
                //dset.Relations.Add(relat);
            }
            //DTO.UserInfo user = Session["UserGuest"] as DTO.UserInfo;
            foreach (DataRow row in dset.Tables["dtQuest"].Rows)
            {
                row["Creation_Time"] = iToday;
                //row["User_ID"] = user.ID;
            }
            //lbMin.Text = testInf.Duration_Time.ToString();
            //lbSec.Text = "00";
            RanDomQuestion(dset, testInf.Random_Answers_S, testInf.Random_Answers_O, No);
            if (testInf.Random_Question_S || testInf.Random_Question_O)
                dset = RebuildDataSet(dset);

            return true;
        }
        private DataSet RebuildDataSet(DataSet dset)
        {
            DataSet result = dset.Clone();
            int index = 1;
            foreach (DataRow row in dset.Tables["dtQuest"].Rows)
            {
                DataRow newRow = result.Tables["dtQuest"].NewRow();
                newRow.ItemArray = row.ItemArray;
                newRow["Line"] = index;
                DataRow[] arrAnsRow = dset.Tables["dtAnswer"].Select("Test_Log_No = " + row["No"].ToString() + " and Test_Log_Line = " + row["Line"].ToString());
                int indexA = 1;
                foreach (DataRow ansRow in arrAnsRow)
                {
                    DataRow newARow = result.Tables["dtAnswer"].NewRow();
                    newARow.ItemArray = ansRow.ItemArray;
                    newARow["Test_Log_Line"] = index;
                    newARow["Rank"] = indexA;
                    result.Tables["dtAnswer"].Rows.Add(newARow);
                    indexA++;
                }
                result.Tables["dtQuest"].Rows.Add(newRow);
                index++;
            }
            return result;
        }

        private void RanDomQuestion(DataSet dset, bool Random_Answers_S, bool Random_Answers_O, int No)
        {
            if (Random_Answers_S || Random_Answers_O)
            {
                DTO.Test_Log_AnswerInfo tmp = new DTO.Test_Log_AnswerInfo();
                DataTable dtAnswer = tmp.ToDataTable();
                dtAnswer.Columns.Add("AnsName");
                dtAnswer.TableName = "dtAnswer";
                dset.Tables.Add(dtAnswer);
                BUS.AnswerControl ansCtr = new BUS.AnswerControl();
                foreach (DataRow row in dset.Tables["dtQuest"].Rows)
                {
                    int iLine = Convert.ToInt32(row["Line"].ToString());
                    DataTable dt = ansCtr.Get_RandByIDQuestion(Convert.ToInt64(row["Question_ID"].ToString()), ref sErr);
                    foreach (DataRow asnRow in dt.Rows)
                    {
                        tmp = new DTO.Test_Log_AnswerInfo();
                        tmp.Answer_ID = Convert.ToInt64(asnRow["ID"]);
                        tmp.Test_Log_Line = iLine;
                        tmp.Test_Log_No = No;
                        tmp.Rank = dt.Rows.IndexOf(row);
                        DataRow tmpRow = tmp.ToDataRow(dset.Tables["dtAnswer"]);
                        tmpRow["AnsName"] = asnRow["Description"];
                        dset.Tables["dtAnswer"].Rows.Add(tmpRow);
                    }
                }
            }
            else
            {
                BUS.Test_Log_AnswerControl ansCtr = new BUS.Test_Log_AnswerControl();
                DataTable dtAnswer = ansCtr.GetLogByNo(No, ref sErr);
                dtAnswer.TableName = "dtAnswer";
                dset.Tables.Add(dtAnswer.Copy());
            }
        }

        protected void cboType_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            dgvList.Rebind();
            LoadComboCate();
            LoadComboTopic();
        }



        protected void cboANAL_T0_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadComboTopic();
        }
    }
}
